package com.liit.controller.weixin.process;

import java.sql.Timestamp;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import cn.liit.weixin.core.basic.accesstoken.AccessTokenSupport;
import cn.liit.weixin.core.config.Config;
import cn.liit.weixin.message.model.req.ReqBaseMessage;
import cn.liit.weixin.message.model.req.ScanSubscribeEventMessage;
import cn.liit.weixin.message.model.req.SubscribeUnsubscribeEventMessage;
import cn.liit.weixin.message.model.resp.RespBaseMessage;
import cn.liit.weixin.message.model.resp.TextMessage;
import cn.liit.weixin.message.process.receive.ReceiveProcessor;
import cn.liit.weixin.userinfo.model.UserInfo;
import cn.liit.weixin.userinfo.utils.Util;

import com.liit.entity.WeixinUserFormMap;
import com.liit.mapper.WeixinUserMapper;
import com.liit.spring.SpringUtils;
import com.liit.util.Common;

/**
 * 
 * @author dingweibo
 * @Title: SubscribeMsgProcess.java
 * @Description: 关注消息处理器
 * @date 2016年3月23日
 */
public class SubscribeMsgProcess extends ReceiveProcessor {

	private static final Logger logger = LoggerFactory.getLogger(SubscribeMsgProcess.class);

	public SubscribeMsgProcess(String msgType, String event) {
		super(msgType, event);
	}

	@Override
	public RespBaseMessage doProcess(ReqBaseMessage reqBaseMessage) {
		RespBaseMessage respBaseMessage = null;
		try {
			String openid = reqBaseMessage.getFromUserName();
			UserInfo userInfo = Util.getUserInfo(AccessTokenSupport.getAccess_token(), openid);

			WeixinUserMapper mapper = SpringUtils.getBean(WeixinUserMapper.class);
			List<WeixinUserFormMap> wxUsers = mapper.findByAttribute("openid", openid, WeixinUserFormMap.class);
			if (CollectionUtils.isEmpty(wxUsers)) {
				// 添加微信用户
				WeixinUserFormMap weixinUser = new WeixinUserFormMap();
				weixinUser.put("openid", openid);
				weixinUser.put("nickname", Common.removeEmoji(userInfo.getNickname()));
				weixinUser.put("sex", userInfo.getSex());
				weixinUser.put("city", userInfo.getCity());
				weixinUser.put("province", userInfo.getProvince());
				weixinUser.put("headImgUrl", userInfo.getHeadimgurl());
				weixinUser.put("subscribeTime", new Timestamp(System.currentTimeMillis()));
				weixinUser.put("groupId", userInfo.getGroupid());
				mapper.addEntity(weixinUser);
			} else {
				// 更新微信用户信息
				WeixinUserFormMap weixinUser = wxUsers.get(0);
				weixinUser.put("nickname", Common.removeEmoji(userInfo.getNickname()));
				weixinUser.put("headImgUrl", userInfo.getHeadimgurl());
				weixinUser.put("groupId", userInfo.getGroupid());
				mapper.editEntity(weixinUser);
			}

			// 带参数扫码关注
			if (reqBaseMessage instanceof ScanSubscribeEventMessage) {

				// 获取扫码参数
				ScanSubscribeEventMessage req = (ScanSubscribeEventMessage) reqBaseMessage;
				if (StringUtils.isBlank(req.getEventKey())) {
					throw new NullPointerException("eventKey is null!");
				}
				String param = req.getEventKey().substring(8);// eventKey以qrscene_开头

				ScanMsgProcess.scanEvent(openid, param);

			} else if (reqBaseMessage instanceof SubscribeUnsubscribeEventMessage) {// 普通关注
				respBaseMessage = new TextMessage("您好，欢迎关注闵行区社会组织公共活动服务平台——【绿色伙伴】\n\n"
						+ "点击菜单【<a href='" + Config.notifyurl + "/weixin/user/listparty.shtml'>活动推荐</a>】，查看最新最热活动：亲子互动、法律援助，慈善公益，社会服务，家庭生活，科普教育...\n\n"
						+ "若您有其他想要了解或咨询的问题，都可以用力输入，“绿色伙伴”将第一时间为您解答！ （报名、签到、评价、赚积分、换礼品......）");
			}
		} catch (Exception e) {
			logger.error("关注微信异常", e);
		}
		return respBaseMessage;
	}
}
